import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String severIp, int severPort) throws IOException {
        socket = new Socket(severIp, severPort);
    }

    public void start(){
        System.out.println("客户端启动");
        Scanner sc = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while(true){
                //从客户端接受请求
                System.out.println("->");
                String request = sc.next();
                //将请求发送回服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //确保数据是真正发送出去了
                printWriter.flush();
                //从服务器读取响应
                Scanner scanner = new Scanner(inputStream);
                String respond = scanner.next();
                System.out.println(respond);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9991);
        tcpEchoClient.start();
    }
}
